package com.example.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.common.ConstantConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class UpLoadUtil {
	
	private static final Logger LOG = LoggerFactory.getLogger(UpLoadUtil.class);

	/**
	 * 
	 * @param localFilePath 上传文件的路径   。如果是Windows情况下，格式是 D:\\qiniu\\test.png 。  linux格式是   /home/qiniu/test.png;
	 * @param key 文件名称
	 * @return   返回文件下载地址
	 * @throws QiniuException 
	 * @throws UnsupportedEncodingException 
	 */
	public static final String uploadFile(String localFilePath,String key) throws QiniuException, UnsupportedEncodingException{
		String finalUrl = null;
		Configuration cfg = new Configuration(Zone.zone2());
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		Auth auth = Auth.create(ConstantConfig.getConfig("qiniu.accessKey"), ConstantConfig.getConfig("qiniu.secretKey"));
		String upToken = auth.uploadToken(ConstantConfig.getConfig("qiniu.bucket"));
		    Response response = uploadManager.put(localFilePath, key, upToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			String fileName = putRet.key;
			String domainOfBucket = ConstantConfig.getConfig("qiniu.downURL");
			String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		    finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
		return finalUrl;
	}
	
	
	public static final String uploadFile(File file,String key) throws QiniuException, UnsupportedEncodingException, FileNotFoundException{
		InputStream is = null;
		is = new FileInputStream(file);
		
		
		String finalUrl = null;
		Configuration cfg = new Configuration(Zone.zone2());
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		Auth auth = Auth.create(ConstantConfig.getConfig("qiniu.accessKey"), ConstantConfig.getConfig("qiniu.secretKey"));
		String upToken = auth.uploadToken(ConstantConfig.getConfig("qiniu.bucket"));
		    Response response = uploadManager.put(is, key, upToken,null,null);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			String fileName = putRet.key;
			String domainOfBucket = ConstantConfig.getConfig("qiniu.downURL");
			String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		    finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
		return finalUrl;
	}
	
}
